package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.service.*;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.RecommendPersonVo;
import com.tanhua.server.vo.TodayBest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TanHuaServiceImpl implements TanHuaService {

    @Value("${tanhua.default.recommend.users}")
    String defaultRecommendUsers;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private QuestionService questionService;
    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;
    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Autowired
    private IMService imService;

    @Override
    public RecommendPersonVo queryUserInfo(Long userId) {

        UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
        if(ObjectUtil.isEmpty(userInfo)){
            return null;
        }
        RecommendPersonVo recommendPersonVo=new RecommendPersonVo();
        recommendPersonVo.setAge(userInfo.getAge());
        recommendPersonVo.setTags(userInfo.getTags().split(","));
        recommendPersonVo.setSex(userInfo.getSex().toString().toLowerCase());
        recommendPersonVo.setNickname(userInfo.getNickName());
        recommendPersonVo.setId(userInfo.getId());
        recommendPersonVo.setAvatar(userInfo.getLogo());

        //缘分值
        User user = UserThreadLocal.get();
        recommendPersonVo.setFateValue(this.recommendUserService.queryScore(userId, user.getId()).longValue());
         //记录来访用户
        this.visitorsApi.saveVisitor(userId, user.getId(), "个人主页");
        return recommendPersonVo;
    }

    @Override
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (ObjectUtil.isNotEmpty(question)){
            return question.getTxt();
        }
        //没有查询到问题返回一个固定的问题
        return this.questionService.queryQuestion(-1L).getTxt();
    }

    @Override
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoById(user.getId());
        Map<String,Object> msg=new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("huanXinId", "HX_" + user.getId());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);
        return this.huanXinApi.sendMsgFromAdmin("HX_"+userId, HuanXinMessageType.TXT, JSONUtil.toJsonStr(msg));
    }

    @Override
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        if (ObjectUtil.isEmpty(userLocationVo)) {
            return ListUtil.empty();
        }
        PageInfo<UserLocationVo> pageInfo = this.userLocationApi.queryUserFromLocation(userLocationVo.getLongitude()
                , userLocationVo.getLatitude()
                , Double.valueOf(distance), 1, 50);
        List<UserLocationVo> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return ListUtil.empty();
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        if (StrUtil.equalsIgnoreCase(gender,"man")){
            wrapper.eq("sex", SexEnum.MAN);
        }else if (StrUtil.equalsIgnoreCase(gender,"woman")){
            wrapper.eq("sex", SexEnum.WOMAN);
        }
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(wrapper);
        if (CollUtil.isEmpty(userIds)){
            return ListUtil.empty();
        }
        List<NearUserVo> nearUserVos=new ArrayList<>();
        NearUserVo nearUserVo=null;
        for (UserLocationVo record :records){
            //排除自己
            if(ObjectUtil.equals(record.getUserId(), user.getId())){
                continue;
            }
            for (UserInfo userInfo : userInfos) {
                if(ObjectUtil.equals(record.getUserId(),userInfo.getUserId())){
                    nearUserVo=new NearUserVo();
                    nearUserVo.setUserId(record.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVos.add(nearUserVo);
                    break;
                }
            }

        }
        return nearUserVos;
    }

    @Override
    public List<TodayBest> queryCardsList() {

        //查询到的50条数据，并不是用来直接展现，需要从这50条数据中随机返回一些数据
        User user = UserThreadLocal.get();
        int count=50;
        List<RecommendUser> recommendUsers=this.recommendUserService.queryCardList(user.getId(),count);
        if (CollUtil.isEmpty(recommendUsers)) {
            recommendUsers = new ArrayList<>();
            //默认推荐用户
            String[] split = StrUtil.split(defaultRecommendUsers, ",");
            RecommendUser recommendUser=null;
            for (String userId : split) {
                recommendUser=new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(user.getId());
                recommendUsers.add(recommendUser);
            }

        }
        int showCount = Math.min(10, recommendUsers.size());
        List<RecommendUser> result = new ArrayList<>();
        Collections.shuffle(recommendUsers);
        for (int i = 0; i < showCount; i++) {
            RecommendUser recommendUser = recommendUsers.get(i);
            result.add(recommendUser);
        }
        List<Object> userIds = CollUtil.getFieldValues(result, "userId");
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoByUserIdList(userIds);
        List<TodayBest> todayBestList=new ArrayList<>();
        TodayBest todayBest=null;
        for (RecommendUser recommendUser : recommendUsers) {
            for (UserInfo userInfo : userInfos) {
                if (ObjectUtil.equals(recommendUser.getUserId(),userInfo.getUserId())) {
                    todayBest=new TodayBest();
                    todayBest.setId(userInfo.getUserId());
                    todayBest.setTags(userInfo.getTags().split(","));
                    todayBest.setNickname(userInfo.getNickName());
                    todayBest.setAvatar(userInfo.getLogo());
                    todayBest.setAge(userInfo.getAge());
                    todayBest.setSex(userInfo.getSex().getValue()==1?"man":"woman");
                    todayBest.setFateValue(Convert.toLong(recommendUser.getScore()));
                    todayBestList.add(todayBest);
                    break;
                }
            }
        }

        return todayBestList;
    }

    @Override
    public boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean result = this.userLikeApi.likeUser(user.getId(), likeUserId);
        if (!result) {
            return false;
        }
        if (this.userLikeApi.isLike(likeUserId,user.getId())){
            //相互喜欢 成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    @Override
    public boolean notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.notLikeUser(user.getId(),likeUserId);
    }
}
